#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string>
#include <cstdio>
#include <unistd.h>

const int gdefaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66;
const int mod = 0666;

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class Shm
{
private:
    int _shmid;
    int _size;
    void *_virtual_addr;
    void CreateHelper(int flg)
    {
        key_t k = ftok(pathname.c_str(), projid);
        if (k < 0)
        {
            ERR_EXIT("ftok\n");
        }
        printf("key: 0x%x\n", k);
        _shmid = shmget(k, gsize, flg);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("_shmid: %d\n", _shmid);
    }

public:
    Shm() : _shmid(gdefaultid), _size(gsize)
    {
    }
    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | 0666);
    }
    void Get()
    {
        CreateHelper(IPC_CREAT);
    }
    bool VirtualAddr()
    {
        void *_virtual_addr = shmat(_shmid, nullptr, 0);
        if ((long long)_virtual_addr < 0)
        {
            ERR_EXIT("shmat");
        }
        std::cout << "virtual_address" << _virtual_addr << '\n';
        return true;
    }
    void Destory()
    {
        if (_shmid == gdefaultid)
            return;
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if (n > 0)
        {
            printf("shmctl delete shm: %d success!\n", _shmid);
        }
        else
        {
            ERR_EXIT("shmclt");
        }
    }

    ~Shm() {}
};